package org.steven.crm.core.service.accesstoken;

import org.steven.crm.core.exception.BusinessErrors;
import org.steven.crm.core.exception.ServiceException;
import org.steven.crm.core.service.BaseService;
import com.steven.xdb.dbmanager.DBManager;
import com.steven.xdb.pagination.query.AbstractQueryDataList;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Author wuzw
 * @Date 2023/12/25 15:10
 * @Version 1.0
 */
public class AccessTokenService extends BaseService {
    @Override
    protected String getTable() {
        return "accessToken";
    }

    @Override
    protected AbstractQueryDataList getQueryDataList() {
        return null;
    }

    @Override
    protected String getDataSourceName() {
        return null;
    }

    public Map<String, String> create(String clientId, String userId) throws Exception {
        String token = "";
        Map<String, String> k = new HashMap<>();
        k.put("clientId", clientId);
        k.put("userId", userId);

        Map<String, String> data = DBManager.queryOne(getSession(), getTable(), k);
        if (data.isEmpty()) {
            token = UUID.randomUUID().toString();
            k.put("token", token);
            return this.create(k);
        } else {
            token = UUID.randomUUID().toString();

            Map<String, String> v = new HashMap<>();
            v.put("token", token);
            return this.update(data.get("id"), v);
        }
    }

    public Map<String, String> readByToken(String token) throws Exception {
        Map<String, String> k = new HashMap<>();
        k.put("token", token);
        return DBManager.queryOne(getSession(), getTable(), k);
    }

    public Map<String, String> validate(String token) throws Exception {
        Map<String, String> k = new HashMap<>();
        k.put("token", token);
        Map<String, String> data = DBManager.queryOne(getSession(), getTable(), k);
        if (data.isEmpty()) {
            throw new ServiceException(BusinessErrors.AUTH_USER_CODE_WRONG);
        }

        String expireTime = data.get("expireTime");
        if (StringUtils.isNotEmpty(expireTime) && Long.parseLong(expireTime) < System.currentTimeMillis()) {
            throw new ServiceException(BusinessErrors.AUTH_TOKEN_EXPIRED);
        }

        return data;
    }

    public void delete(String clientId, String userId) throws Exception {
        Map<String, String> k = new HashMap<>();
        k.put("clientId", clientId);
        k.put("userId", userId);
        DBManager.delete(getSession(), getTable(), k);
    }
}
